<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class Net extends Common
{

	//列表
    public function index()
    {

        $duojxs = $this->request->get('duojxs');
        $this->assign(array('duojxs'=>$duojxs));

        $where = [];
        $where['t.isdel'] = 0;
        $zhankai = $this->request->get('zhankai');
        $this->assign(array('zhankai'=>$zhankai));
        $sn = $this->request->get('sn');
        $this->assign(array('sn'=>$sn));
        if(trim($sn)){
            $where['t.sn'] = $sn;
        }

        $title = $this->request->get('title');
        $this->assign(array('title'=>$title));
        if(trim($title)){
            $where['t.title'] = ['like','%'.$title.'%'];
        }

        $city = $this->request->get('city');
        $this->assign(array('city'=>$city));
        if(trim($city)){
            $where['t.city'] = ['exp','in(select id from cg_market_city where title like \'%'.$city.'%\')'];
        }

        $zone = $this->request->get('zone');
        $this->assign(array('zone'=>$zone));
        if(trim($zone)){
            $where['t.zoning'] = ['exp','in(select id from cg_market_zoning where title like \'%'.$zone.'%\')'];
        }

        $provice = $this->request->get('provice');
        $this->assign(array('provice'=>$provice));
        if(trim($provice)){
            $where['t.provice'] = ['exp','in(select id from cg_market_provice where title like \'%'.$provice.'%\')'];
        }


        $oneCType = $this->request->get('oneCType');
        $this->assign(array('oneCType'=>$oneCType));
        if(trim($oneCType)){
            $where['t.system_id'] = ['exp','in(select t.id from cg_system t join cg_channel_types1 t2 on t2.id=t.oneCType where t2.title like \'%'.$oneCType.'%\')'];
        }

        $twoCType = $this->request->get('twoCType');
        $this->assign(array('twoCType'=>$twoCType));
        if(trim($twoCType)){
            $where['t.system_id'] = ['exp','in(select t.id from cg_system t join cg_channel_types2 t2 on t2.id=t.twoCType where t2.title like \'%'.$twoCType.'%\')'];
        }

        $cate = $this->request->get('cate');
        $this->assign(array('cate'=>$cate));
        if(trim($cate)){
            $where['t.cat'] = $cate;
        }

        $iskey = $this->request->get('iskey');
        $this->assign(array('iskey'=>$iskey));
        if(''!=$iskey){
            $where['t.iskey'] = $iskey;
        }

        $guide = $this->request->get('guide');
        $this->assign(array('guide'=>$guide));
        if(''!=trim($guide)){
            $where['t.guide'] = $guide;
        }

        $sample = $this->request->get('sample');
        $this->assign(array('sample'=>$sample));
        if(''!=trim($sample)){
            $where['t.sample'] = $sample;
        }
        $direct = $this->request->get('direct');
        $this->assign(array('direct'=>$direct));
        if(''!=trim($direct)){
            $where['t.direct'] = $direct;
        }

        $grade_s = $this->request->get('grade');
        $this->assign(array('grade_s'=>$grade_s));
        if(trim($grade_s)){
            $where['t.grade'] = $grade_s;
        }

        $jxs_sn = $this->request->get('jxs_sn');
        $this->assign(array('jxs_sn'=>$jxs_sn));
        if(trim($jxs_sn)){
            $where['t.system_id'] = ['exp',"in(select system_id from cg_system_jxs tt join cg_jxs tt2 on tt2.id=tt.jxs_id where tt2.sn like '%{$jxs_sn}%' )"];
        }

        $jxs_title = $this->request->get('jxs_title');
        $this->assign(array('jxs_title'=>$jxs_title));
        if(trim($jxs_title)){

            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_jxs')->where(['title'=>['like','%'.$jxs_title.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['system_id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['t.system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select id from cg_jxs where title like '%{$jxs_title}%')"];
            }

        }

        $jxs_zoning = $this->request->get('jxs_zoning');
        $this->assign(array('jxs_zoning'=>$jxs_zoning));
        if($jxs_zoning){
            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_market_zoning')->where(['title'=>['like','%'.$jxs_zoning.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $jxs_ids = Db::table('cg_jxs')->where(['zoning'=>['in',$jxs_ids]])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select t.id from cg_jxs t join cg_market_zoning t2 on t2.id=t.zoning where t2.title like '%{$jxs_title}%')"];
            }

        }
        $jxs_provice = $this->request->get('jxs_provice');
        $this->assign(array('jxs_provice'=>$jxs_provice));
        if($jxs_provice){
            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_market_provice')->where(['title'=>['like','%'.$jxs_provice.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $jxs_ids = Db::table('cg_jxs')->where(['provice'=>['in',$jxs_ids]])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select t.id from cg_jxs t join cg_market_provice t2 on t2.id=t.provice where t2.title like '%{$jxs_provice}%')"];
            }

        }
        $jxs_city = $this->request->get('jxs_city');
        $this->assign(array('jxs_city'=>$jxs_city));
        if($jxs_city){
            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_market_city')->where(['title'=>['like','%'.$jxs_city.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $jxs_ids = Db::table('cg_jxs')->where(['city'=>['in',$jxs_ids]])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select t.id from cg_jxs t join cg_market_city t2 on t2.id=t.city where t2.title like '%{$jxs_city}%')"];
            }

        }
        $system_sn = $this->request->get('system_sn');
        $this->assign(array('system_sn'=>$system_sn));
        if($system_sn){
            $where['t.system_id'] = ['exp','in(select id from cg_system where sn like \''.$system_sn.'\')'];
        }
        $system_title = $this->request->get('system_title');
        $this->assign(array('system_title'=>$system_title));
        if($system_title){
            $where['t.system_id'] = ['exp','in(select id from cg_system where title like \''.$system_title.'\')'];
        }

        $stuff = $this->request->get('stuff');
        $this->assign(array('stuff'=>$stuff));
        if($stuff){
            //根据模糊查询规则把admin对应的id全部查询出来
            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
            $str = [];
            foreach($ids as $k=>$v){
                if($k==0)
                    $str[] = " like '%\"$v[id]\"%' ";
                else
                    $str[] = " t.stuff like '%\"$v[id]\"%' ";
            }
            $str = implode('or',$str);

            $where['t.stuff'] = array('exp',$str);
        }


        //地址经纬度
        $address = $this->request->get('address');
        $this->assign(array('address'=>$address));
        if($address){
            switch ($address){
                case 1:
                    $where['t.lat'] = ['exp','is not null and t.lat <> \'\''];
                    $where['t.lng'] = ['exp','is not null and t.lng <> \'\''];
                    $where['t.detailAddress'] = ['exp','is null or t.detailAddress=\'\''];
                    break;
                case 2:
                    $where['t.lat'] = ['exp','is null or t.lat=\'\''];
                    $where['t.lng'] = ['exp','is null or t.lng=\'\''];
                    $where['t.detailAddress'] = ['exp','is not null and t.detailAddress<>\'\''];
                    break;
                case 3:
                    $where['t.lat'] = ['exp','is null or t.lat=\'\''];
                    $where['t.lng'] = ['exp','is null or t.lng=\'\''];
                    $where['t.detailAddress'] = ['exp','is null or t.detailAddress=\'\''];
                    break;
                default:
                    $where['t.lat'] = ['exp','is not null and t.lat <> \'\''];
                    $where['t.lng'] = ['exp','is not null and t.lng <> \'\''];
                    $where['t.detailAddress'] = ['exp','is not null and t.detailAddress<>\'\''];
            }
        }


        if(trim($duojxs)&&$duojxs==1){
            $count = Db::table('cg_net t')->where($where)->count();
        }else{
            $count = Db::table('cg_net t')->join('cg_system t2','t2.id=t.system_id')->join('cg_system_jxs t3','t3.system_id=t2.id')->where($where)->count();
        }

        if(trim($duojxs)&&$duojxs==1){
            $data = Db::table('cg_net t')->order("t.id desc")->where($where)->paginate(10,$count);
        }else{
            $data = Db::table('cg_net t')->field('t.*,t3.jxs_id')->order('t.id desc')->join('cg_system t2','t2.id=t.system_id','left')->join('cg_system_jxs t3','t3.system_id=t2.id','left')->where($where)->paginate(10,$count);
        }
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
            $data[$k]['zoning'] = Db::table('cg_market_zoning')->where('id',$v['zoning'])->value('title');
            $data[$k]['provice'] = Db::table('cg_market_provice')->where('id',$v['provice'])->value('title');
            $data[$k]['city'] = Db::table('cg_market_city')->where('id',$v['city'])->value('title');
            if($v['stuff']){
                $temp = unserialize($v['stuff']);
                $temp = implode(',',$temp);
                $temp = Db::query("select em_name from employee where id in(".$temp.")");
                $temp2 = [];
                foreach($temp as $v1){
                    $temp2[] = $v1['em_name'];
                }
                $data[$k]['stuff'] = implode(',',$temp2);
            }

            $data[$k]['system_sn'] = Db::table('cg_system')->where('id',$v['system_id'])->value('sn');
            $data[$k]['system_title'] = Db::table('cg_system')->where('id',$v['system_id'])->value('title');

            //所属经销商编号
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->where('t.system_id',$v['system_id'])->field('t2.sn')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['sn'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_sn'] = $temp;

            }else{
                $data[$k]['system_jxs_sn'] = Db::table('cg_jxs')->where('id',$v['jxs_id'])->value('sn');

            }

            //所属经销商名称
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->where('t.system_id',$v['system_id'])->field('t2.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_title'] = $temp;

            }else{
                $data[$k]['system_jxs_title'] = Db::table('cg_jxs')->where('id',$v['jxs_id'])->value('title');

            }

            //所属经销商大区
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_zoning t3','t3.id=t2.zoning')->where('t.system_id',$v['system_id'])->field('t3.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_zoning'] = $temp;

            }else{
                $data[$k]['system_jxs_zoning'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$v['jxs_id'])->value('t2.title');

            }

            //所属经销商省份
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_provice t3','t3.id=t2.provice')->where('t.system_id',$v['system_id'])->field('t3.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_provice'] = $temp;

            }else{
                $data[$k]['system_jxs_provice'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$v['jxs_id'])->value('t2.title');

            }

            //所属经销商城市
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_city t3','t3.id=t2.city')->where('t.system_id',$v['system_id'])->field('t3.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_city'] = $temp;

            }else{
                $data[$k]['system_jxs_city'] = Db::table('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$v['jxs_id'])->value('t2.title');

            }


            //分区负责人
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_zoning t3','t3.id=t2.zoning')->join('employee t4','t4.id=t3.head')->where('t.system_id',$v['system_id'])->field('t4.em_name')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['em_name'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_zoning_head'] = $temp;

            }else{
                $data[$k]['system_jxs_zoning_head'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->join('employee t3','t3.id=t2.head')->where('t.id',$v['jxs_id'])->value('t3.em_name');

            }
            //省份负责人
            if(trim($duojxs)&&$duojxs==1){

                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_provice t3','t3.id=t2.provice')->join('employee t4','t4.id=t3.head')->where('t.system_id',$v['system_id'])->field('t4.em_name')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['em_name'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_provice_head'] = $temp;

            }else{

                $data[$k]['system_jxs_provice_head'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->join('employee t3','t3.id=t2.head')->where('t.id',$v['jxs_id'])->value('t3.em_name');

            }

            //城市负责人
            if(trim($duojxs)&&$duojxs==1){

                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_city t3','t3.id=t2.city')->join('employee t4','t4.id=t3.head')->where('t.system_id',$v['system_id'])->field('t4.em_name')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['em_name'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_city_head'] = $temp;

            }else{

                $data[$k]['system_jxs_city_head'] = Db::table('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->join('employee t3','t3.id=t2.head')->where('t.id',$v['jxs_id'])->value('t3.em_name');

            }

            //经销商业务人员
            if(trim($duojxs)&&$duojxs==1){

                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->where('t.system_id',$v['system_id'])->field('t2.stuff')->select();

                foreach($temp as $k1=>$v1){
                    $t = unserialize($v1['stuff']);
                    $t = implode(',',$t);
                    $t = Db::query("select em_name from employee where id in(".$t.")");

                    foreach($t as $k2=>$v2){
                        $t[$k2] = $v2['em_name'];
                    }
                    $temp[$k1] =  implode(',',$t);
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_stuff'] = $temp;

            }else{

                $temp = Db::table('cg_jxs')->where('id',$v['jxs_id'])->value('stuff');
                if($temp){
                    $temp = unserialize($temp);
                    $temp = implode(',',$temp);
                    $temp = Db::query("select em_name from employee where id in(".$temp.")");
                    $temp2 = [];
                    foreach($temp as $v1){
                        $temp2[] = $v1['em_name'];
                    }
                    $data[$k]['system_jxs_stuff'] =  implode(',',$temp2);
                }else{
                    $data[$k]['system_jxs_stuff'] = '';
                }

            }


            $data[$k]['exec_provice'] = Db::table('cg_provice')->where('id',$v['exec_provice'])->value('title');
            $data[$k]['exec_city'] = Db::table('cg_city')->where('id',$v['exec_city'])->value('title');
            $data[$k]['exec_county'] = Db::table('cg_county')->where('id',$v['exec_county'])->value('title');
            $data[$k]['oneCType'] = Db::table('cg_channel_types1 t')->join('cg_system t2','t2.oneCType = t.id')->where('t2.id',$v['system_id'])->value('t.title');
            $data[$k]['twoCType'] = Db::table('cg_channel_types2 t')->join('cg_system t2','t2.twoCType = t.id')->where('t2.id',$v['system_id'])->value('t.title');
            $data[$k]['cat'] = Db::table('cg_networktype')->where('id',$v['cat'])->value('title');
        }

        //查询网点分类
        $cat = Db::table('cg_networktype')->select();
        $this->assign('cat',$cat);

        //查询网点等级
        $grade = Db::table('cg_networklevel')->select();
        $this->assign('grade',$grade);

        $this->assign('data',$data);
        $this->assign('page',$page);
         $this->assign('maxpage',$maxpage);
        $this->assign('count',$count);
        return $this->fetch();
    }

    public function add(){
        $id = $this->request->param('system_id');
        if($_POST){

            $validate = new Valid([
                'title|网点名称'  => 'require|max:100|checkJxsmc|unique:cg_net',
                'sn|网点编号'  => 'unique:cg_net',
                'cat|网点类型'  => 'require',
                'grade|网点等级'  => 'require',
                'em_num|雇员人数'  => 'number',
                'area|店面面积'  => 'number',
                'layers|店面层数'  => 'number',
                'shelf_num|同品类货架节数'  => 'number',
                'cashiers|收银台数'  => 'number',
                'area_same_cat|同品类面积'  => 'number',
                'lanpushs_same_cat|同品类地堆数'  => 'number',
                'frames_same_cat|同品类端架数'  => 'number',
                'cooptime|开始合作日期'  => 'dateFormat:Y-m-d',
                'starttime|网店开店日期'  => 'dateFormat:Y-m-d',
                'zoning|营销分区'  => 'require',
                'provice|营销省份'  => 'require',
                'city|营销城市'  => 'require',
                'detailAddress|详细地址'  => 'require',
                'lgs_rcv_addr|收货地址1'  => 'require',
                'lgs_rcv_one|收货人1'  => 'require',
                'lgs_rcv_phone|联系电话1'  => 'require|cgPhoneOrMobile',
            ]);
            $data = Request::instance()->post();

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            //网点联络信息验证
            if(isset($data['systemContact'])&&is_array($data['systemContact'])&&count($data['systemContact'])>0){
                foreach($data['systemContact']['name'] as $k=>$v){
                    if($v == ''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"网点联络信息-联系人姓名不能为空"
                        ]);die;
                    }
                    if($data['systemContact']['phone1'][$k] == ''||$data['systemContact']['phone2'][$k] == ''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"网点联络信息-联系电话不能为空"
                        ]);die;
                    }
                    if($data['systemContact']['mobile'][$k] == ''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"网点联络信息-手机不能为空"
                        ]);die;
                    }
                }
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"网点联络信息-至少填一条"
                ]);die;
            }

            //网点已进场条码验证
            if(isset($data['barcode'])&&is_array($data['barcode'])&&count($data['barcode'])>0){

                $valid1 = new Valid([
                    'prod|产品'  => 'require',
                    'intime|进场时间'  => 'dateFormat:Y-m-d',
                    'infee|进场费'  => 'number',
                    'retailPrice|卖场零售价'  => 'number'
                ]);

                foreach($data['barcode']['prod'] as $k=>$v){
                    if($v!=''){
                        $temp = [];
                        $temp['prod'] = $v;
                        $temp['intime'] = $data['barcode']['intime'][$k];
                        $temp['infee'] = $data['barcode']['infee'][$k];
                        $temp['retailPrice'] = $data['barcode']['retailPrice'][$k];

                        if (!$valid1->check($temp)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$valid1->getError()
                            ]);die;
                        }
                    }


                }
            }

            //网点竞品验证
            if(isset($data['com'])&&is_array($data['com'])&&count($data['com'])>0){

                $valid1 = new Valid([
                    'cate|竞品品类'  => 'require',
                    'id|竞品名称'  => 'require',
                    'price|零售价'  => 'require',
                    'specs|竞品规格'  => 'require',
                ]);

                foreach($data['com']['cate'] as $k=>$v){
                    $temp = [];
                    $temp['cate'] = $v;
                    $temp['id'] = $data['com']['id'][$k];
                    $temp['price'] = $data['com']['price'][$k];
                    $temp['specs'] = $data['com']['specs'][$k];
                    $temp['brief'] = $data['com']['brief'][$k];

                    if (!$valid1->check($temp)) {
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>$valid1->getError()
                        ]);die;
                    }

                }
            }

            if($data['stuff']){
                $data['stuff'] = explode(',',$data['stuff']);
                $data['stuff'] = serialize($data['stuff']);
            }

            //系统编号为空则自动生成
            if(empty($data['sn'])){
                $year=date("Y")-2000;
                $day=date("md");
                $ckyear=$year.$day;
                $max = Db::query("select max(sn) m from cg_net where sn like '{$ckyear}%' limit 1");
                if($max[0]["m"])
                    $data["sn"]=$max[0]["m"]+1;
                else
                    $data['sn']=$ckyear."0001";
                
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['cooptime'] = strtotime($data['cooptime']);
            $data['starttime'] = strtotime($data['starttime']);
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            if($data['attach']){
                $attachids = $data['attach'];
                $data['attach'] = serialize(explode(',',$data['attach']));
            }


            $systemContact = $data['systemContact'];
            unset($data['systemContact']);

            $barcode = $data['barcode'];
            unset($data['barcode']);

            if(isset($data['com'])){
                $com = $data['com'];
                unset($data['com']);
            }

            $bool = Db::table('cg_net')->insert($data);
            if(false !== $bool){
                $insetid = Db::table('cg_net')->getLastInsID();

                //更新附件表
                if(isset($attachids)){

                    Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$insetid,'target_table'=>'cg_net'));
                }

                //增加附属联系信息表
                if(isset($systemContact)&&is_array($systemContact)){
                    $temp  = [];

                    foreach($systemContact['name'] as $k=>$v){
                        if($v=='')
                            continue;
                        $temp[] = [
                            'name'=>$v,
                            'net_id'=>$insetid,
                            'phone'=>$systemContact['phone1'][$k].'-'.$systemContact['phone2'][$k],
                            'mobile'=>$systemContact['mobile'][$k],
                            'fax'=>$systemContact['fax1'][$k].'-'.$systemContact['fax2'][$k],
                            'email'=>$systemContact['email'][$k],
                            'job'=>$systemContact['job'][$k],
                            'cuser'=>$_SESSION['think']['employee_id'],
                            'ctime'=>time(),
                            'puser'=>$_SESSION['think']['employee_id'],
                            'ptime'=>time(),
                        ];
                    }
                    Db::name('cg_net_ci')->insertAll($temp);
                }

                //增加条码标
                if(isset($barcode)&&is_array($barcode)){
                    $temp  = [];

                    foreach($barcode['prod'] as $k=>$v){
                        if($v=='')
                            continue;
                        $temp[] = [
                            'net_id'=>$id,
                            'prod'=>$v,
                            'intime'=>$barcode['intime'][$k],
                            'infee'=>$barcode['infee'][$k],
                            'retailPrice'=>$barcode['retailPrice'][$k]
                        ];
                    }
                    Db::name('cg_net_barcode')->insertAll($temp);
                }

                //增加竞品
                if(isset($com)&&is_array($com)){
                    $temp  = [];

                    foreach($com['cate'] as $k=>$v){
                        if($v=='')
                            continue;
                        $temp[] = [
                            'net_id'=>$id,
                            'cate'=>$v,
                            'name'=>$com['id'][$k],
                            'price'=>$com['price'][$k],
                            'specs'=>$com['specs'][$k],
                            'brief'=>$com['brief'][$k]
                        ];
                    }
                    Db::name('cg_net_competitor')->insertAll($temp);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"添加成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"添加失败"
                ]);die;
            }

        }

        //查询基本信息并赋值
        $this->basic();

        //查询竞品分类
        $competitor = Db::table('competitor_category')->field('id,category_name')->select();
        $this->assign('com_cate',$competitor);

        //查询所属系统信息
        $system_info = Db::table('cg_system')->where('id',$id)->field('title,stuff')->find();
        $temp = unserialize($system_info['stuff']);
        $temp = implode(',',$temp);
        $temp = Db::query("select em_name from employee where id in(".$temp.")");
        $temp2 = [];
        foreach($temp as $v1){
            $temp2[] = $v1['em_name'];
        }
        $system_info['stuff'] = implode(',',$temp2);

        $this->assign('system_info',$system_info);
        $this->assign('id',$id);

        //查询所属经销商信息
        $sys=db("cg_system")->where("id",$id)->find();
        $this->assign("sys",$sys);
        $jxs = Db::table('cg_system')->where('id',$id)->value('jxs');
        $jxs = Db::table('cg_jxs')->where('id',$jxs)->field('title,sn,zoning,provice,city')->find();
        $jxs['zoning_head'] = Db::table('cg_market_zoning t')->join('employee t2','t.head=t2.id')->where('t.id',$jxs['zoning'])->value('t2.em_name');
        $jxs['provice_head'] = Db::table('cg_market_provice t')->join('employee t2','t.head=t2.id')->where('t.id',$jxs['provice'])->value('t2.em_name');
        $jxs['city_head'] = Db::table('cg_market_city t')->join('employee t2','t.head=t2.id')->where('t.id',$jxs['city'])->value('t2.em_name');
        $jxs['market'] = Db::table('cg_market_zoning')->where('id',$jxs['zoning'])->value('title').'-'.Db::table('cg_market_provice')->where('id',$jxs['provice'])->value('title').'-'.Db::table('cg_market_city')->where('id',$jxs['city'])->value('title');
        $this->assign('jxs',$jxs);


        //查询一级渠道类型
        $channel1 = Db::table('cg_system t')->join('cg_channel_types1 t2','t2.id=t.oneCType')->where('t.id',$id)->value('t2.title');
        $channel2 = Db::table('cg_system t')->join('cg_channel_types2 t2','t2.id=t.twoCType')->where('t.id',$id)->value('t2.title');
        $this->assign('channel1',$channel1);
        $this->assign('channel2',$channel2);

        return $this->fetch('form');
    }

    public function format(){
        $catid = $this->request->get('id');

        //查询该分类下的所有竞品
        echo $data = Db::table('competitor')->where('id',$catid)->value('format');

    }

    //新增网点第一步-选择对应系统
    public function addNet(){

        $title = $this->request->get('title');
        $sn = $this->request->get('sn');

        $this->assign(array('title'=>$title));
        $this->assign(array('sn'=>$sn));

        $where = [];
        $where['t.isdel'] = 0;

        if($title)
            $where['title'] = array('like','%'.$title.'%');
        if($sn)
            $where['sn'] = array('like','%'.$sn.'%');

        $count = Db::table('cg_system t')->where($where)->count();
        $data = Db::table('cg_system t')->field('id,title,sn')->order("t.id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch('addNet');
    }

    /**
     * 修改基本信息
     * @return mixed
     * @throws \think\Exception
     */
    public function update(){
        $id = $this->request->param('id');

        if($_POST){
            $validate = new Valid([
                'title|网点名称'  => 'require|max:100|checkJxsmc|unique:cg_net',
                'sn|网点编号'  => 'unique:cg_net',
                'cat|网点类型'  => 'require',
                'grade|网点等级'  => 'require',
                'em_num|雇员人数'  => 'number',
                'area|店面面积'  => 'number',
                'layers|店面层数'  => 'number',
                'shelf_num|同品类货架节数'  => 'number',
                'cashiers|收银台数'  => 'number',
                'area_same_cat|同品类面积'  => 'number',
                'lanpushs_same_cat|同品类地堆数'  => 'number',
                'frames_same_cat|同品类端架数'  => 'number',
                'cooptime|开始合作日期'  => 'dateFormat:Y-m-d',
                'starttime|网店开店日期'  => 'dateFormat:Y-m-d',
                'zoning|营销分区'  => 'require',
                'provice|营销省份'  => 'require',
                'city|营销城市'  => 'require',
            ]);
            $data = Request::instance()->post();
            $data['id'] = $id;
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['cooptime'] = strtotime($data['cooptime']);
            $data['starttime'] = strtotime($data['starttime']);
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            //记录日志-备份原记录
            $old = $this->log_start($id);
            $bool = Db::table('cg_net')->where('id',$id)->update($data);
            if(false !== $bool){
                //记录日志-开始记录
                $this->log_end($id,$old);
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_net')->where('id',$id)->find();

        //查询基本信息并赋值
        $this->basic();

        //查询一级渠道类型
        $channel1 = Db::table('cg_system t')->join('cg_channel_types1 t2','t2.id=t.oneCType')->where('t.id',$data['system_id'])->value('t2.title');
        $channel2 = Db::table('cg_system t')->join('cg_channel_types2 t2','t2.id=t.twoCType')->where('t.id',$data['system_id'])->value('t2.title');

        $this->assign('channel1',$channel1);
        $this->assign('channel2',$channel2);
        $this->assign('data',$data);
        $this->assign('id',$id);

        //查询所有省份
        $provice = Db::table('cg_market_provice')->where('zoning',$data['zoning'])->select();
        $this->assign('provice',$provice);

        $city = Db::table('cg_market_city')->where('provice',$data['provice'])->select();
        $this->assign('city',$city);

        $provice = Db::table('cg_provice')->select();
        $this->assign('exec_provice',$provice);

        $city = Db::table('cg_city')->where('provice',$data['exec_provice'])->select();
        $this->assign('exec_city',$city);

        $city = Db::table('cg_county')->where('city',$data['exec_county'])->select();
        $this->assign('exec_county',$city);

        return $this->fetch('form_updatebasic');
    }

    //修改联系人信息
    public function form_contact(){
        $id = $this->request->param('id');

        if($_POST){

            $data = Request::instance()->post();
            //网点联络信息验证
            if(isset($data['systemContact'])&&is_array($data['systemContact'])&&count($data['systemContact'])>0){
                foreach($data['systemContact']['name'] as $k=>$v){
                    if($v == ''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"网点联络信息-联系人姓名不能为空"
                        ]);die;
                    }
                    if($data['systemContact']['phone1'][$k] == ''||$data['systemContact']['phone2'][$k] == ''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"网点联络信息-联系电话不能为空"
                        ]);die;
                    }
                    if($data['systemContact']['mobile'][$k] == ''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"网点联络信息-手机不能为空"
                        ]);die;
                    }
                }
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"网点联络信息-至少填一条"
                ]);die;
            }


            $bool = true ;
            //增加附属联系信息表
            if(isset($data['systemContact'])&&is_array($data['systemContact'])){
                $temp  = [];

                foreach($data['systemContact']['name'] as $k=>$v){
                    if($v=='')
                        continue;
                    $temp[] = [
                        'name'=>$v,
                        'net_id'=>$id,
                        'phone'=>$data['systemContact']['phone1'][$k].'-'.$data['systemContact']['phone2'][$k],
                        'mobile'=>$data['systemContact']['mobile'][$k],
                        'fax'=>$data['systemContact']['fax1'][$k].'-'.$data['systemContact']['fax2'][$k],
                        'email'=>$data['systemContact']['email'][$k],
                        'job'=>$data['systemContact']['job'][$k],
                        'cuser'=>$_SESSION['think']['employee_id'],
                        'ctime'=>time(),
                        'puser'=>$_SESSION['think']['employee_id'],
                        'ptime'=>time(),
                    ];
                }
                $bool = Db::name('cg_net_ci')->insertAll($temp);

            }

            if(false !== $bool){

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_net_ci')->where('net_id',$id)->select();

        //查询基本信息并赋值
        $this->basic();

        $this->assign('data',$data);
        return $this->fetch();
    }

    //修改物流信息
    public function form_wuliu(){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'lgs_rcv_addr|收货地址1'  => 'require',
                'lgs_rcv_one|收货人1'  => 'require',
                'lgs_rcv_phone|联系电话1'  => 'require|cgPhoneOrMobile',
            ]);
            $data = Request::instance()->post();
            $data['id'] = $id;
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            //记录日志-备份原记录
            $old = $this->log_start($id);
            $bool = Db::table('cg_net')->where('id',$id)->update($data);
            //记录日志-开始记录
            $this->log_end($id,$old);

            if(false !== $bool){

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_net')->where('id',$id)->field('lgs_rcv_addr,lgs_rcv_one,lgs_rcv_phone,lgs_rcv_addr2,lgs_rcv_one2,lgs_rcv_phone2,lgs_rcv_addr3,lgs_rcv_one3,lgs_rcv_phone3')->find();

        $this->assign('data',$data);
        return $this->fetch();
    }

    //修改负责人
    public function form_fuzeren(){
        $id = $this->request->param('id');

        if($_POST){

            $data = Request::instance()->post();

            if($data['stuff']){
                $data['stuff'] = explode(',',$data['stuff']);
                $data['stuff'] = serialize($data['stuff']);
            }

            //记录日志-备份原记录
            $old = $this->log_start($id);
            $bool = Db::table('cg_net')->where('id',$id)->update($data);

            if(false !== $bool){
//记录日志-开始记录
                $this->log_end($id,$old);
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_net')->where('id',$id)->value('stuff');
        if($data){
            $data = unserialize($data);
            foreach($data as $k=>$v){
                $data[$k] = Db::table('employee')->field('id,em_name')->where('id',$v)->find();
            }
        }

        $this->assign('data',$data);
        return $this->fetch();
    }

    //修改进场条码
    public function form_barcode(){
        if($_POST){


            $ren = $this->request->post('ren/a');
            if(count($ren)<1){
                echo json_encode(['success'=>false,'请选择人员']);die;
            }
            $intime = $this->request->post('intime');
            if(!$intime){
                echo json_encode(['success'=>false,'请填写入场时间']);die;
            }
            $infee = $this->request->post('infee');
            if(!$infee){
                echo json_encode(['success'=>false,'请填写入场费']);die;
            }
            $rp = $this->request->post('retailPrice');
            if(!$rp){
                echo json_encode(['success'=>false,'请填写零售价格']);die;
            }
            $insert = [];
            $infee = round($infee/count($ren),2);

            foreach($ren as $v){
                $data = [];
                $data['prod'] = $v;
                $data['net_id'] = $this->request->post('net_id');
                $data['intime'] = strtotime($intime);
                $data['infee'] = $infee;
                $data['retailPrice'] = $rp;
                $insert[] = $data;
            }

            $bool = Db::table('cg_net_barcode')->insertAll($insert);
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }
        echo $this->fetch();
    }
    /**
     * 添加和修改基本信息需要首先查询的公共数据
     * @param $id
     */
    public function basic(){

        //查询网点分类
        $cat = Db::table('cg_networktype')->select();
        $this->assign('cat',$cat);

        //查询网点等级
        $grade = Db::table('cg_networklevel')->select();
        $this->assign('grade',$grade);

        //查询网点所属营销区域
        $zoning = Db::table('cg_market_zoning')->select();
        $this->assign('zoning',$zoning);

        //查询网点所属行政省份
        $exec_provice = Db::table('cg_provice')->select();
        $this->assign('exec_provice',$exec_provice);


    }

    public function view(){
        $id = $this->request->param('id');
        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        //查询联系人信息
        $ci = Db::table('cg_net_ci')->where('net_id',$id)->select();
        $data['ci'] = $ci;
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function view1(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $data['stuff'] = unserialize($data['stuff']);

        if($data['stuff']){
            foreach ($data['stuff'] as $k=>$v){
                $data['stuff'][$k] = Db::table('employee')->where('id',$v)->value('em_name');
            }
            $data['stuff'] = implode(',',$data['stuff']);
        }

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view2(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);

        //导购员列表
        $dg = db('cg_net_dg')->where('net_id',$id)->select();
        $this->assign('dg',$dg);
        return $this->fetch();
    }
    public function view3(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view4(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view5(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view6(){
        $id = $this->request->param('id');
        $chakanhuibao = $this->request->get('chakanhuibao');

        if($chakanhuibao){
            return $this->fetch('chakanhuibao');
            die;
        }

        if($_POST){
            $a = $this->request->post('a');
            if($a==2){
                $status = $this->request->post('status');
                $bar_id = $this->request->post('bar_id');
                $bool = Db::table('cg_net_barcode')->where('id',$bar_id)->update(['status'=>$status]);
//                echo Db::table('cg_net_barcode')->getLastSql();
                if(false !== $bool){
                    echo json_encode(['success'=>true,'msg'=>'ok']);die;
                }else{
                    echo json_encode(['success'=>false,'msg'=>'error']);die;
                }
            }else{
                $data = [];
                $data['tuichangshijian'] = $this->request->post('tuichangshijian');
                $data['tuichangyuanyin'] = $this->request->post('tuichangyuanyin');
                $data['tuichang'] = 1;
                if(!$data['tuichangshijian']){
                    echo json_encode(['success'=>false,'msg'=>'请填写退场时间']);die;
                }
                if(!$data['tuichangyuanyin']){
                    echo json_encode(['success'=>false,'msg'=>'请填写退场原因']);die;
                }
                $data['tuichangshijian'] =  strtotime(trim($data['tuichangshijian']));
                $ids = $this->request->post('bar_id');
                $bool = Db::table('cg_net_barcode')
                    ->where('id',$ids)
                    ->update($data);
//            echo Db::table('cg_net')->getLastSql();

                if(false !== $bool){
                    echo json_encode(['success'=>true,'msg'=>'ok']);die;
                }else{
                    echo json_encode(['success'=>false,'msg'=>'error']);die;
                }
            }

        }

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);

        $yituichang = $this->request->get('yituichang');
        if($yituichang==1)
            $where['tuichang'] = 1;
        else
            $where['tuichang'] = 0;
        $where['net_id'] = $id;

        $barcode = Db::table('cg_net_barcode')->order('id desc')->where($where)->select();
        foreach($barcode as $k=>$v){
            $barcode[$k]['prod'] = Db::table('pro_products')->where('id',$v['prod'])->value('pro_name');
            $barcode[$k]['pro_sku'] = Db::table('pro_products')->where('id',$v['prod'])->value('pro_sku');
        }
        $this->assign('barcode',$barcode);
        return $this->fetch();
    }
    public function barcode(){
        $id = $this->request->param('id');
        $data = Db::table('cg_net_barcode')->order('id desc')->where('net_id',$id)->select();
        foreach($data as $k=>$v){
            $data[$k]['prod'] = Db::table('pro_products')->where('id',$v['prod'])->value('pro_name');
            $data[$k]['pro_sku'] = Db::table('pro_products')->where('id',$v['prod'])->value('pro_sku');
        }
        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view7(){
        $id = $this->request->param('id');
        $addProductDevide = $this->request->get('addProductDevide');

        if($_POST){
            $data = [];
            $data['brands'] = $this->request->post('brands');
            $data['category'] = $this->request->post('category');
            $data['jxs'] = $this->request->post('jxs');
            $data['brief'] = $this->request->post('brief');
            $s_id = $this->request->post('s_id');
            $data['net_id'] = $id;
            if(!trim($data['jxs'])){
                echo json_encode(['success'=>false,'msg'=>'请选择经销商']);die;
            }
            if(!trim($data['brands'])){
                echo json_encode(['success'=>false,'msg'=>'请选择品牌']);die;
            }

            if($s_id){
                $bool = Db::table('cg_net_product_suplly')->where('id',$s_id)->update($data);
            }else
                $bool = Db::table('cg_net_product_suplly')->insert($data);
            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }


        if($addProductDevide){
            //查询系统id
            $system_id = Db::table('cg_net')->where('id',$id)->value('system_id');
            $this->assign('system_id',$system_id);
            $s_id = $this->request->get('s_id');
            $this->assign('s_id',$s_id);
            if($s_id){
                $supply = Db::table('cg_net_product_suplly')->where('id',$s_id)->find();
                $supply['brands'] = Db::table('pro_brands')->where('id','in',$supply['brands'])->field('id,brand_name title')->select();
                $supply['category'] = Db::table('pro_category')->where('id','in',$supply['category'])->field('id,category_name title')->select();
                $supply['jxs_title'] = Db::table('cg_jxs')->where('id',$supply['jxs'])->value('title');
                $this->assign('supply',$supply);
            }
            return $this->fetch('addProductDevide');
        }

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);

        //查询产品供应
        $supply = Db::table('cg_net_product_suplly')->where('net_id',$id)->select();
        foreach($supply as $k=>$v){
            $supply[$k]['jxs'] = Db::table('cg_jxs')->where('id',$v['jxs'])->value('title');
            $supply[$k]['brands'] = Db::table('pro_brands')->where('id','in',$v['brands'])->field('brand_name')->select();
            foreach($supply[$k]['brands'] as $k1=>$v1){
                $supply[$k]['brands'][$k1] = $v1['brand_name'];
            }
            $supply[$k]['brands'] = implode(',',$supply[$k]['brands']);
            $supply[$k]['category'] = Db::table('pro_category')->where('id','in',$v['category'])->field('category_name')->select();
            foreach($supply[$k]['category'] as $k1=>$v1){
                $supply[$k]['category'][$k1] = $v1['category_name'];
            }
            $supply[$k]['category'] = implode(',',$supply[$k]['category']);
        }
        $this->assign('supply',$supply);
        return $this->fetch();
    }

    public function view8(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view9(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view10(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view11(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view12(){
        $id = $this->request->param('id');
        $addc = $this->request->param('addc');

        $chakanhuibao = $this->request->get('chakanhuibao');

        //查看汇报
        if($chakanhuibao){
            return $this->fetch('chakanhuibao_compe');
            die;
        }

        //添加竞品
        if($_POST){
            $data = Request::instance()->post();

            //判断是修改还是增加
            if(isset($data['id'])){
                $bool = Db::table('cg_net_competitor')->where('id',$data['id'])->update($data);
                if(false !== $bool){
                    echo  json_encode([
                        "success"=>true,
                        "msg"=>'ok'
                    ]);
                }else{
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>'error'
                    ]);
                }
            }else{
                //网点竞品验证
                if(isset($data['com'])&&is_array($data['com'])&&count($data['com'])>0){

                    $valid1 = new Valid([
                        'cate|竞品品类'  => 'require',
                        'id|竞品名称'  => 'require',
                        'price|零售价'  => 'require|number',
                        'specs|竞品规格'  => 'require',
                    ]);

                    foreach($data['com']['cate'] as $k=>$v){
                        $temp = [];
                        $temp['cate'] = $v;
                        $temp['id'] = $data['com']['id'][$k];
                        $temp['price'] = $data['com']['price'][$k];
                        $temp['specs'] = $data['com']['specs'][$k];
                        $temp['brief'] = $data['com']['brief'][$k];

                        if (!$valid1->check($temp)) {
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$valid1->getError()
                            ]);die;
                        }

                    }
                }
                $com = $data['com'];
                //增加竞品
                $bool = true;
                if(isset($com)&&is_array($com)){
                    $temp  = [];

                    foreach($com['cate'] as $k=>$v){
                        if($v=='')
                            continue;
                        $temp[] = [
                            'net_id'=>$id,
                            'cate'=>$v,
                            'name'=>$com['id'][$k],
                            'price'=>$com['price'][$k],
                            'specs'=>$com['specs'][$k],
                            'brief'=>$com['brief'][$k]
                        ];
                    }
                    $bool = Db::name('cg_net_competitor')->insertAll($temp);

                }

                if(false !== $bool){
                    echo  json_encode([
                        "success"=>true,
                        "msg"=>'ok'
                    ]);
                }else{
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>'error'
                    ]);
                }
            }

            die;
        }

        //添加竞品模板
        if($addc){
            $c_id = $this->request->param('c_id');
            $this->assign('c_id',$c_id);

            //查询竞品分类
            $competitor = Db::table('competitor_category')->field('id,category_name')->select();
            $this->assign('com_cate',$competitor);

            if($c_id){
                $compe = Db::table('cg_net_competitor')->where('id',$c_id)->find();
                $this->assign('compe',$compe);

                //查询竞品分类下的所有竞品
                $all_compe = Db::table('competitor')->where('category_id',$compe['cate'])->field('id,c_name')->select();
                $this->assign('all_compe',$all_compe);

                return $this->fetch('form_compe_update');
            }else{
                return $this->fetch('form_compe');
            }


        }

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);

        //查询竞品列表
        $compe = Db::table('cg_net_competitor')->where('net_id',$id)->select();
        if($compe){
            foreach($compe as $k=>$v){
                $compe[$k]['cate'] = Db::table('competitor_category')->where('id',$v['cate'])->value('category_name');
                $compe[$k]['name'] = Db::table('competitor')->where('id',$v['name'])->value('c_name');
            }
        }
        $this->assign('supply',$compe);
        return $this->fetch();
    }
    public function view13(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view14(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }
    public function view15(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);

        //查询附件
        $attach = Db::table('cg_net')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);

        return $this->fetch();
    }
    public function view16(){
        $id = $this->request->param('id');
        $woyaoping = $this->request->param('woyaoping');
        $subEvaluation = $this->request->param('subEvaluation');

        if($subEvaluation){
            $data = [];
            $data['a1'] = $this->request->post('a1');
            $data['a2'] = $this->request->post('a2');
            $data['a3'] = $this->request->post('a3');
            $data['a4'] = $this->request->post('a4');
            $data['a5'] = $this->request->post('a5');
            $data['a6'] = $this->request->post('a6');
            $data['cuser'] = Session::get('employee_id');
            $data['ctime'] = time();
            $data['net_id'] = $id;
            $evaluation = Db::table('cg_net_evaluation')->where(['net_id'=>$data['net_id'],'cuser'=>Session::get('employee_id')])->count();
            if($evaluation>0){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"不能重复评价"
                ]);die;
            }
            $bool = Db::table('cg_net_evaluation')->insert($data);
            if(false !== $bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"评价成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"评价失败"
                ]);die;
            }
        }
        if($woyaoping){
            return $this->fetch('woyaoping');
        }

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);


        //查询评价信息
        $count = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->count();
        $this->assign('count',$count);
        $a1s = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->field(' sum(a1)')->value('sum(a1)');
        $a1s = $count?$a1s/$count:$a1s;
        $this->assign('a1s',$a1s);
        $a2s = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->field(' sum(a1)')->value('sum(a2)');
        $a2s = $count?$a2s/$count:$a2s;
        $this->assign('a2s',$a2s);
        $a3s = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->field(' sum(a1)')->value('sum(a2)');
        $a3s = $count?$a3s/$count:$a3s;
        $this->assign('a3s',$a3s);
        $a4s = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->field(' sum(a1)')->value('sum(a2)');
        $a4s = $count?$a4s/$count:$a4s;
        $this->assign('a4s',$a4s);
        $a5s = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->field(' sum(a1)')->value('sum(a2)');
        $a5s = $count?$a5s/$count:$a5s;
        $this->assign('a5s',$a5s);
        $a6s = Db::table('cg_net_evaluation')->where(['net_id'=>$id,'cuser'=>Session::get('employee_id')])->field(' sum(a1)')->value('sum(a2)');
        $a6s = $count?$a6s/$count:$a6s;
        $this->assign('a6s',$a6s);

        $this->assign('count',$count);


        return $this->fetch();
    }
    public function view17(){
        $id = $this->request->param('id');

        //查询基本信息（cg_net表里所有字段）
        $data = $this->searchBasic($id);

        $this->assign('data',$data);
        return $this->fetch();
    }

    public  function searchBasic($id){
        $data = Db::table('cg_net')->where('id',$id)->find();
        $data['system_title'] = Db::table('cg_system')->where('id',$data['system_id'])->value('title');
        $data['system_sn'] = Db::table('cg_system')->where('id',$data['system_id'])->value('sn');
        $data['jxs_title'] = Db::table('cg_system t')->join('cg_jxs t2','t2.id=t.jxs')->where('t.id',$data['system_id'])->value('t2.title');
        $data['jxs_sn'] = Db::table('cg_system t')->join('cg_jxs t2','t2.id=t.jxs')->where('t.id',$data['system_id'])->value('t2.sn');
        $jxs_id = Db::table('cg_system t')->where('t.id',$data['system_id'])->value('jxs');
        $data['jxs_zoning'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t.zoning = t2.id')->where('t.id',$jxs_id)->value('t2.title');
        $data['jxs_provice'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t.provice = t2.id')->where('t.id',$jxs_id)->value('t2.title');
        $data['jxs_city'] = Db::table('cg_jxs t')->join('cg_market_city t2','t.city = t2.id')->where('t.id',$jxs_id)->value('t2.title');
        $data['oneCType'] = Db::table('cg_system t')->join('cg_channel_types1 t2','t2.id=t.oneCType')->where('t.id',$data['system_id'])->value('t2.title');
        $data['twoCType'] = Db::table('cg_system t')->join('cg_channel_types2 t2','t2.id=t.twoCType')->where('t.id',$data['system_id'])->value('t2.title');
        $data['zoning'] = Db::table('cg_market_zoning')->where('id',$data['zoning'])->value('title');
        $data['provice'] = Db::table('cg_market_provice')->where('id',$data['provice'])->value('title');
        $data['city'] = Db::table('cg_market_city')->where('id',$data['city'])->value('title');
        $data['exec_provice'] = Db::table('cg_provice')->where('id',$data['exec_provice'])->value('title');
        $data['exec_city'] = Db::table('cg_city')->where('id',$data['exec_city'])->value('title');
        $data['exec_county'] = Db::table('cg_county')->where('id',$data['exec_county'])->value('title');
        return $data;
    }

    /**
     * 维护系统
     * @return mixed
     * @throws \think\Exception
     */
    public function whSystem(){
        $id = $this->request->param('id');

        $data = Db::table('cg_system_group')->where('id',$id)->find();

        //查询没分组的系统
        $meifenzu = Db::table('cg_system')->field('id,title')->where('groupid',0)->select();
        $yifenzu = Db::table('cg_system')->field('id,title')->where('groupid','<>',0)->select();


        $this->assign('data',$data);
        $this->assign('meifenzu',$meifenzu);
        $this->assign('yifenzu',$yifenzu);
        $this->assign('id',$id);

        return $this->fetch();
    }

    //    批量设置分组
    public function batchSet(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['groupid'] = $pid;
        $bool = Db::table('cg_system')->where('id','in',$id)->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }

    //    批量取消设置分组
    public function batchSet2(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['groupid'] = 0;
        $bool = Db::table('cg_system')->where('id','in',$id)->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }


    /**
     * 删除
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['isdel'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
    /**
     * 清空网站经纬度
     * @throws \think\Exception
     */
    public function clearLnglat(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"清空错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['lat'=>null,'lng'=>null]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"清空成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"清空失败"
            ]);die;
        }
    }
    /**
     * 删除
     * @throws \think\Exception
     */
    public function deleteContact(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net_ci')->where(array('id'=>$id))->update(['isdel'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }


    /**
     * 启用
     * @throws \think\Exception
     */
    public function qiyongContact(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net_ci')->where(array('id'=>$id))->update(['isdel'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"启用成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"启用失败"
            ]);die;
        }
    }
    /**
     * 启用网点
     * @throws \think\Exception
     */
    public function qiyong(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['isdel'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"启用成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"启用失败"
            ]);die;
        }
    }



    /**
     * 追加
     * @return mixed
     */
    public function zhuijia(){
        return $this->fetch();
    }

    //选择经销商
    public function selectJXS(){
        return $this->fetch();
    }

    //选择品牌
    public function selectBrands(){
        return $this->fetch();
    }

    //选择品类
    public function selectCategory(){
        return $this->fetch();
    }
    //返回分区经销商树数据
    public function zonetreeajax(){
        $data = Db::table('cg_market_zoning')->where('isdel',0)->field('id,title')->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')->where(array('zoning'=>$v['id']))->field('id,title')->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')->where(array('provice'=>$vv['id']))->field('id,title')->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3['name'] = $v3['title'];
                    //查城市
                    $t3 = Db::table('cg_jxs')->where(array('city'=>$v3['id']))->field('id,title name')->select();//查经销商
                    $temp3['children'] = $t3;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    /**
     * 查询经销商的部分信息
     */
    public function findJxs(){
        $id = $this->request->post('id');
        $data = Db::table('cg_jxs')->where('id',$id)->field('sn,zoning,provice,city')->find();
        $data['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$data['city'])->value('t2.em_name');
        $data['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$data['provice'])->value('t2.em_name');
        $data['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$data['zoning'])->value('t2.em_name');
        echo json_encode($data);die;
    }

    /**
     * 返回经销商json数据
     */
    public function productjson(){
        //查询所有省份
        $data = Db::table('pro_products')->field('pro_name title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }

    /**
     * 回收站
     * @return mixed
     */
    public function isdel()
    {

        $duojxs = $this->request->get('duojxs');
        $this->assign(array('duojxs'=>$duojxs));

        $where = [];
        $where['t.isdel'] = 1;
        $zhankai = $this->request->get('zhankai');
        $this->assign(array('zhankai'=>$zhankai));
        $sn = $this->request->get('sn');
        $this->assign(array('sn'=>$sn));
        if(trim($sn)){
            $where['t.sn'] = $sn;
        }

        $title = $this->request->get('title');
        $this->assign(array('title'=>$title));
        if(trim($title)){
            $where['t.title'] = ['like','%'.$title.'%'];
        }

        $city = $this->request->get('city');
        $this->assign(array('city'=>$city));
        if(trim($city)){
            $where['t.city'] = ['exp','in(select id from cg_market_city where title like \'%'.$city.'%\')'];
        }

        $zone = $this->request->get('zone');
        $this->assign(array('zone'=>$zone));
        if(trim($zone)){
            $where['t.zoning'] = ['exp','in(select id from cg_market_zoning where title like \'%'.$zone.'%\')'];
        }

        $provice = $this->request->get('provice');
        $this->assign(array('provice'=>$provice));
        if(trim($provice)){
            $where['t.provice'] = ['exp','in(select id from cg_market_provice where title like \'%'.$provice.'%\')'];
        }


        $oneCType = $this->request->get('oneCType');
        $this->assign(array('oneCType'=>$oneCType));
        if(trim($oneCType)){
            $where['t.system_id'] = ['exp','in(select t.id from cg_system t join cg_channel_types1 t2 on t2.id=t.oneCType where t2.title like \'%'.$oneCType.'%\')'];
        }

        $twoCType = $this->request->get('twoCType');
        $this->assign(array('twoCType'=>$twoCType));
        if(trim($twoCType)){
            $where['t.system_id'] = ['exp','in(select t.id from cg_system t join cg_channel_types2 t2 on t2.id=t.twoCType where t2.title like \'%'.$twoCType.'%\')'];
        }

        $cate = $this->request->get('cate');
        $this->assign(array('cate'=>$cate));
        if(trim($cate)){
            $where['t.cat'] = $cate;
        }

        $iskey = $this->request->get('iskey');
        $this->assign(array('iskey'=>$iskey));
        if(''!=$iskey){
            $where['t.iskey'] = $iskey;
        }

        $guide = $this->request->get('guide');
        $this->assign(array('guide'=>$guide));
        if(''!=trim($guide)){
            $where['t.guide'] = $guide;
        }

        $sample = $this->request->get('sample');
        $this->assign(array('sample'=>$sample));
        if(''!=trim($sample)){
            $where['t.sample'] = $sample;
        }
        $direct = $this->request->get('direct');
        $this->assign(array('direct'=>$direct));
        if(''!=trim($direct)){
            $where['t.direct'] = $direct;
        }

        $grade_s = $this->request->get('grade');
        $this->assign(array('grade_s'=>$grade_s));
        if(trim($grade_s)){
            $where['t.grade'] = $grade_s;
        }

        $jxs_sn = $this->request->get('jxs_sn');
        $this->assign(array('jxs_sn'=>$jxs_sn));
        if(trim($jxs_sn)){
            $where['t.system_id'] = ['exp',"in(select system_id from cg_system_jxs tt join cg_jxs tt2 on tt2.id=tt.jxs_id where tt2.sn like '%{$jxs_sn}%' )"];
        }

        $jxs_title = $this->request->get('jxs_title');
        $this->assign(array('jxs_title'=>$jxs_title));
        if(trim($jxs_title)){

            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_jxs')->where(['title'=>['like','%'.$jxs_title.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['system_id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['t.system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select id from cg_jxs where title like '%{$jxs_title}%')"];
            }

        }

        $jxs_zoning = $this->request->get('jxs_zoning');
        $this->assign(array('jxs_zoning'=>$jxs_zoning));
        if($jxs_zoning){
            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_market_zoning')->where(['title'=>['like','%'.$jxs_zoning.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $jxs_ids = Db::table('cg_jxs')->where(['zoning'=>['in',$jxs_ids]])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select t.id from cg_jxs t join cg_market_zoning t2 on t2.id=t.zoning where t2.title like '%{$jxs_title}%')"];
            }

        }
        $jxs_provice = $this->request->get('jxs_provice');
        $this->assign(array('jxs_provice'=>$jxs_provice));
        if($jxs_provice){
            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_market_provice')->where(['title'=>['like','%'.$jxs_provice.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $jxs_ids = Db::table('cg_jxs')->where(['provice'=>['in',$jxs_ids]])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select t.id from cg_jxs t join cg_market_provice t2 on t2.id=t.provice where t2.title like '%{$jxs_provice}%')"];
            }

        }
        $jxs_city = $this->request->get('jxs_city');
        $this->assign(array('jxs_city'=>$jxs_city));
        if($jxs_city){
            if(trim($duojxs)&&$duojxs==1){ //一行经销商

                $jxs_ids = Db::table('cg_market_city')->where(['title'=>['like','%'.$jxs_city.'%']])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $jxs_ids = implode(',',$jxs_ids);
                $jxs_ids = Db::table('cg_jxs')->where(['city'=>['in',$jxs_ids]])->field('id')->select();
                foreach($jxs_ids as $k=>$v){
                    $jxs_ids[$k] = $v['id'];
                }
                $system_ids = Db::table('cg_system_jxs')->where(['jxs_id'=>['in',$jxs_ids]])->field('system_id')->select();
                foreach($system_ids as $k=>$v){
                    $system_ids[$k] = $v['id'];
                }
                $system_ids = implode(',',$system_ids);
                $where['system_id'] = ['in',$system_ids];

            }else{  //默认多行经销商
                $where['t3.jxs_id'] = ['exp',"in(select t.id from cg_jxs t join cg_market_city t2 on t2.id=t.city where t2.title like '%{$jxs_city}%')"];
            }

        }
        $system_sn = $this->request->get('system_sn');
        $this->assign(array('system_sn'=>$system_sn));
        if($system_sn){
            $where['t.system_id'] = ['exp','in(select id from cg_system where sn like \''.$system_sn.'\')'];
        }
        $system_title = $this->request->get('system_title');
        $this->assign(array('system_title'=>$system_title));
        if($system_title){
            $where['t.system_id'] = ['exp','in(select id from cg_system where title like \''.$system_title.'\')'];
        }

        $stuff = $this->request->get('stuff');
        $this->assign(array('stuff'=>$stuff));
        if($stuff){
            //根据模糊查询规则把admin对应的id全部查询出来
            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
            $str = [];
            foreach($ids as $k=>$v){
                if($k==0)
                    $str[] = " like '%\"$v[id]\"%' ";
                else
                    $str[] = " t.stuff like '%\"$v[id]\"%' ";
            }
            $str = implode('or',$str);

            $where['t.stuff'] = array('exp',$str);
        }


        //地址经纬度
        $address = $this->request->get('address');
        $this->assign(array('address'=>$address));
        if($address){
            switch ($address){
                case 1:
                    $where['t.lat'] = ['exp','is not null and t.lat <> \'\''];
                    $where['t.lng'] = ['exp','is not null and t.lng <> \'\''];
                    $where['t.detailAddress'] = ['exp','is null or t.detailAddress=\'\''];
                    break;
                case 2:
                    $where['t.lat'] = ['exp','is null or t.lat=\'\''];
                    $where['t.lng'] = ['exp','is null or t.lng=\'\''];
                    $where['t.detailAddress'] = ['exp','is not null and t.detailAddress<>\'\''];
                    break;
                case 3:
                    $where['t.lat'] = ['exp','is null or t.lat=\'\''];
                    $where['t.lng'] = ['exp','is null or t.lng=\'\''];
                    $where['t.detailAddress'] = ['exp','is null or t.detailAddress=\'\''];
                    break;
                default:
                    $where['t.lat'] = ['exp','is not null and t.lat <> \'\''];
                    $where['t.lng'] = ['exp','is not null and t.lng <> \'\''];
                    $where['t.detailAddress'] = ['exp','is not null and t.detailAddress<>\'\''];
            }
        }


        if(trim($duojxs)&&$duojxs==1){
            $count = Db::table('cg_net t')->where($where)->count();
        }else{
            $count = Db::table('cg_net t')->join('cg_system t2','t2.id=t.system_id')->join('cg_system_jxs t3','t3.system_id=t2.id')->where($where)->count();
        }

        if(trim($duojxs)&&$duojxs==1){
            $data = Db::table('cg_net t')->order("t.id desc")->where($where)->paginate(10,$count);
        }else{
            $data = Db::table('cg_net t')->field('t.*,t3.jxs_id')->order('t.id desc')->join('cg_system t2','t2.id=t.system_id')->join('cg_system_jxs t3','t3.system_id=t2.id')->where($where)->paginate(10,$count);
        }
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
            $data[$k]['zoning'] = Db::table('cg_market_zoning')->where('id',$v['zoning'])->value('title');
            $data[$k]['provice'] = Db::table('cg_market_provice')->where('id',$v['provice'])->value('title');
            $data[$k]['city'] = Db::table('cg_market_city')->where('id',$v['city'])->value('title');
            if($v['stuff']){
                $temp = unserialize($v['stuff']);
                $temp = implode(',',$temp);
                $temp = Db::query("select em_name from employee where id in(".$temp.")");
                $temp2 = [];
                foreach($temp as $v1){
                    $temp2[] = $v1['em_name'];
                }
                $data[$k]['stuff'] = implode(',',$temp2);
            }

            $data[$k]['system_sn'] = Db::table('cg_system')->where('id',$v['system_id'])->value('sn');
            $data[$k]['system_title'] = Db::table('cg_system')->where('id',$v['system_id'])->value('title');

            //所属经销商编号
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->where('t.system_id',$v['system_id'])->field('t2.sn')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['sn'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_sn'] = $temp;

            }else{
                $data[$k]['system_jxs_sn'] = Db::table('cg_jxs')->where('id',$v['jxs_id'])->value('sn');

            }

            //所属经销商名称
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->where('t.system_id',$v['system_id'])->field('t2.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_title'] = $temp;

            }else{
                $data[$k]['system_jxs_title'] = Db::table('cg_jxs')->where('id',$v['jxs_id'])->value('title');

            }

            //所属经销商大区
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_zoning t3','t3.id=t2.zoning')->where('t.system_id',$v['system_id'])->field('t3.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_zoning'] = $temp;

            }else{
                $data[$k]['system_jxs_zoning'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$v['jxs_id'])->value('t2.title');

            }

            //所属经销商省份
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_provice t3','t3.id=t2.provice')->where('t.system_id',$v['system_id'])->field('t3.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_provice'] = $temp;

            }else{
                $data[$k]['system_jxs_provice'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$v['jxs_id'])->value('t2.title');

            }

            //所属经销商城市
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_city t3','t3.id=t2.city')->where('t.system_id',$v['system_id'])->field('t3.title')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['title'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_city'] = $temp;

            }else{
                $data[$k]['system_jxs_city'] = Db::table('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$v['jxs_id'])->value('t2.title');

            }


            //分区负责人
            if(trim($duojxs)&&$duojxs==1){
                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_zoning t3','t3.id=t2.zoning')->join('employee t4','t4.id=t3.head')->where('t.system_id',$v['system_id'])->field('t4.em_name')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['em_name'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_zoning_head'] = $temp;

            }else{
                $data[$k]['system_jxs_zoning_head'] = Db::table('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->join('employee t3','t3.id=t2.head')->where('t.id',$v['jxs_id'])->value('t3.em_name');

            }
            //省份负责人
            if(trim($duojxs)&&$duojxs==1){

                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_provice t3','t3.id=t2.provice')->join('employee t4','t4.id=t3.head')->where('t.system_id',$v['system_id'])->field('t4.em_name')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['em_name'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_provice_head'] = $temp;

            }else{

                $data[$k]['system_jxs_provice_head'] = Db::table('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->join('employee t3','t3.id=t2.head')->where('t.id',$v['jxs_id'])->value('t3.em_name');

            }

            //城市负责人
            if(trim($duojxs)&&$duojxs==1){

                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->join('cg_market_city t3','t3.id=t2.city')->join('employee t4','t4.id=t3.head')->where('t.system_id',$v['system_id'])->field('t4.em_name')->select();
                foreach($temp as $k1=>$v1){
                    $temp[$k1] = $v1['em_name'];
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_city_head'] = $temp;

            }else{

                $data[$k]['system_jxs_city_head'] = Db::table('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->join('employee t3','t3.id=t2.head')->where('t.id',$v['jxs_id'])->value('t3.em_name');

            }

            //经销商业务人员
            if(trim($duojxs)&&$duojxs==1){

                $temp = Db::table('cg_system_jxs t')->join('cg_jxs t2','t.jxs_id=t2.id')->where('t.system_id',$v['system_id'])->field('t2.stuff')->select();

                foreach($temp as $k1=>$v1){
                    $t = unserialize($v1['stuff']);
                    $t = implode(',',$t);
                    $t = Db::query("select em_name from employee where id in(".$t.")");

                    foreach($t as $k2=>$v2){
                        $t[$k2] = $v2['em_name'];
                    }
                    $temp[$k1] =  implode(',',$t);
                }
                $temp = implode('<hr>',$temp);
                $data[$k]['system_jxs_stuff'] = $temp;

            }else{


                $temp = Db::table('cg_jxs')->where('id',$v['jxs_id'])->value('stuff');
                $temp = unserialize($temp);
                $temp = implode(',',$temp);
                $temp = Db::query("select em_name from employee where id in(".$temp.")");
                $temp2 = [];
                foreach($temp as $v1){
                    $temp2[] = $v1['em_name'];
                }
                $data[$k]['system_jxs_stuff'] =  implode(',',$temp2);

            }


            $data[$k]['exec_provice'] = Db::table('cg_provice')->where('id',$v['exec_provice'])->value('title');
            $data[$k]['exec_city'] = Db::table('cg_city')->where('id',$v['exec_city'])->value('title');
            $data[$k]['exec_county'] = Db::table('cg_county')->where('id',$v['exec_county'])->value('title');
            $data[$k]['oneCType'] = Db::table('cg_channel_types1 t')->join('cg_system t2','t2.oneCType = t.id')->where('t2.id',$v['system_id'])->value('t.title');
            $data[$k]['twoCType'] = Db::table('cg_channel_types2 t')->join('cg_system t2','t2.twoCType = t.id')->where('t2.id',$v['system_id'])->value('t.title');
            $data[$k]['cat'] = Db::table('cg_networktype')->where('id',$v['cat'])->value('title');
        }

        //查询网点分类
        $cat = Db::table('cg_networktype')->select();
        $this->assign('cat',$cat);

        //查询网点等级
        $grade = Db::table('cg_networklevel')->select();
        $this->assign('grade',$grade);

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //系统操作日志
    public function log_start($id){
        $data = Db::table('cg_net')->where('id',$id)->find();
        return $data;
    }
    //系统操作日志
    public function log_end($id,$old){
        $new = Db::table('cg_net')->where('id',$id)->find();
        $msg = [];
        if($new&&$old){
            if($old['title'] != $new['title']){
                $msg[] = '网点名称由‘'.$old['title'].'’变成‘'.$new['title'].'’';
            }
            if(trim($old['brief']) != trim($new['brief'])){
                $msg[] = '描述信息由‘'.$old['brief'].'’变成‘'.$new['brief'].'’';
            }
            if($old['zoning'] != $new['zoning']){
                $msg[] = '所属营销大区由‘'.Db::table('cg_market_zoning')->where('id',$old['zoning'])->value('title').'’变成‘'.Db::table('cg_market_zoning')->where('id',$new['zoning'])->value('title').'’';
            }
            if($old['provice'] != $new['provice']){
                $msg[] = '所属营销省份由‘'.Db::table('cg_market_provice')->where('id',$old['provice'])->value('title').'’变成‘'.Db::table('cg_market_provice')->where('id',$new['provice'])->value('title').'’';
            }
            if($old['city'] != $new['city']){
                $msg[] = '所属营销城市由‘'.Db::table('cg_market_city')->where('id',$old['city'])->value('title').'’变成‘'.Db::table('cg_market_city')->where('id',$new['city'])->value('title').'’';
            }

            if($old['exec_provice'] != $new['exec_provice']){
                $msg[] = '所属行政省份由‘'.Db::table('cg_provice')->where('id',$old['exec_provice'])->value('title').'’变成‘'.Db::table('cg_provice')->where('id',$new['exec_provice'])->value('title').'’';
            }
            if($old['exec_city'] != $new['exec_city']){
                $msg[] = '所属行政城市由‘'.Db::table('cg_city')->where('id',$old['exec_city'])->value('title').'’变成‘'.Db::table('cg_city')->where('id',$new['exec_city'])->value('title').'’';
            }
            if($old['exec_county'] != $new['exec_county']){
                $msg[] = '所属行政区县由‘'.Db::table('cg_county')->where('id',$old['exec_county'])->value('title').'’变成‘'.Db::table('cg_county')->where('id',$new['exec_county'])->value('title').'’';
            }

            if($old['sn'] != $new['sn']){
                $msg[] = '网点编号由‘'.$old['sn'].'’变成‘'.$new['sn'].'’';
            }

            if($old['lgs_rcv_addr'] != $new['lgs_rcv_addr']){
                $msg[] = '收货地址1由‘'.$old['lgs_rcv_addr'].'’变成‘'.$new['lgs_rcv_addr'].'’';
            }
            if($old['lgs_rcv_one'] != $new['lgs_rcv_one']){
                $msg[] = '收货人1由‘'.$old['lgs_rcv_one'].'’变成‘'.$new['lgs_rcv_one'].'’';
            }
            if($old['lgs_rcv_phone'] != $new['lgs_rcv_phone']){
                $msg[] = '联系电话1由‘'.$old['lgs_rcv_phone'].'’变成‘'.$new['lgs_rcv_phone'].'’';
            }

            if($old['lgs_rcv_addr2'] != $new['lgs_rcv_addr2']){
                $msg[] = '收货地址2由‘'.$old['lgs_rcv_addr2'].'’变成‘'.$new['lgs_rcv_addr2'].'’';
            }
            if($old['lgs_rcv_one2'] != $new['lgs_rcv_one2']){
                $msg[] = '收货人2由‘'.$old['lgs_rcv_one2'].'’变成‘'.$new['lgs_rcv_one2'].'’';
            }
            if($old['lgs_rcv_phone2'] != $new['lgs_rcv_phone2']){
                $msg[] = '联系电话2由‘'.$old['lgs_rcv_phone2'].'’变成‘'.$new['lgs_rcv_phone2'].'’';
            }

            if($old['lgs_rcv_addr3'] != $new['lgs_rcv_addr3']){
                $msg[] = '收货地址3由‘'.$old['lgs_rcv_addr3'].'’变成‘'.$new['lgs_rcv_addr3'].'’';
            }
            if($old['lgs_rcv_one3'] != $new['lgs_rcv_one3']){
                $msg[] = '收货人3由‘'.$old['lgs_rcv_one3'].'’变成‘'.$new['lgs_rcv_one3'].'’';
            }
            if($old['lgs_rcv_phone3'] != $new['lgs_rcv_phone3']){
                $msg[] = '联系电话3由‘'.$old['lgs_rcv_phone3'].'’变成‘'.$new['lgs_rcv_phone3'].'’';
            }

            if($old['sn'] != $new['sn']){
                $msg[] = '网点编号由‘'.$old['sn'].'’变成‘'.$new['sn'].'’';
            }

            if($old['detailAddress'] != $new['detailAddress']){
                $msg[] = '详细地址由‘'.$old['detailAddress'].'’变成‘'.$new['detailAddress'].'’';
            }

            if($old['stuff'] != $new['stuff']){
                if($old['stuff']&&$new['stuff']){
                    $old['stuff'] = unserialize($old['stuff']);
                    $new['stuff'] = unserialize($new['stuff']);
                    $add = array_diff($new['stuff'],$old['stuff']);
                    $del = array_diff($old['stuff'],$new['stuff']);
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('employee')->where("id in($add)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了业务代表'.$daibiao2;
                    }
                    if($del){
                        $del = implode(',',$del);
                        $daibiao = Db::table('employee')->where("id in($del)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了业务代表'.$daibiao2;
                    }
                }elseif($old['stuff']){
                    $old['stuff'] = unserialize($old['stuff']);

                    if($old['stuff']){
                        $del = implode(',',$old['stuff']);
                        $daibiao = Db::table('employee')->where("id in(".$old['stuff'].")")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了业务代表'.$daibiao2;
                    }
                }else{
                    $new['stuff'] = unserialize($new['stuff']);
                    $add = $new['stuff'];
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('employee')->where("id in($add)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了业务代表'.$daibiao2;
                    }
                }
            }

            if($old['attach'] != $new['attach']){
                if($old['attach']&&$new['attach']){
                    $old['attach'] = unserialize($old['attach']);
                    $new['attach'] = unserialize($new['attach']);
                    $add = array_diff($new['attach'],$old['attach']);
                    $del = array_diff($old['attach'],$new['attach']);
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('annex')->where("id in($add)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了附件'.$daibiao2;
                    }
                    if($del){
                        $del = implode(',',$del);
                        $daibiao = Db::table('annex')->where("id in($del)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了附件'.$daibiao2;
                    }
                }elseif($old['attach']){
                    $old['attach'] = unserialize($old['attach']);

                    if($old['attach']){
                        $del = implode(',',$old['attach']);
                        $daibiao = Db::table('annex')->where("id in(".$old['attach'].")")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了附件'.$daibiao2;
                    }
                }else{
                    $new['attach'] = unserialize($new['attach']);
                    $add = $new['attach'];
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('annex')->where("id in($add)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了附件'.$daibiao2;
                    }
                }
            }

            if($old['isdel'] != $new['isdel']){
                if($old['isdel'] ==1)
                    $msg[] = '从回收站重新启用了该经销商';
                else
                    $msg[] = '把该经销商挪到了回收站';
            }


            if($old['grade'] != $new['grade']){
                $msg[] = '网点等级由‘'.Db::table('cg_networklevel')->where('id',$old['grade'])->value('title').'’变成‘'.Db::table('cg_networklevel')->where('id',$new['grade'])->value('title').'’';
            }
            if($old['em_num'] != $new['em_num']){
                $msg[] = '雇员个数由‘'.$old['em_num'].'’变成‘'.$new['em_num'].'’';
            }
            if($old['area'] != $new['area']){
                $msg[] = '店面面积由‘'.$old['area'].'’变成‘'.$new['area'].'’';
            }
            if($old['layers'] != $new['layers']){
                $msg[] = '店面层数由‘'.$old['layers'].'’变成‘'.$new['layers'].'’';
            }
            if($old['abbr'] != $new['abbr']){
                $msg[] = '网点简称由‘'.$old['abbr'].'’变成‘'.$new['abbr'].'’';
            }
            if($old['shelf_num'] != $new['shelf_num']){
                $msg[] = '同品类货架节数由‘'.$old['shelf_num'].'’变成‘'.$new['shelf_num'].'’';
            }
            if($old['cashiers'] != $new['cashiers']){
                $msg[] = '收银台数由‘'.$old['cashiers'].'’变成‘'.$new['cashiers'].'’';
            }
            if($old['area_same_cat'] != $new['area_same_cat']){
                $msg[] = '同品类面积由‘'.$old['area_same_cat'].'’变成‘'.$new['area_same_cat'].'’';
            }
            if($old['lanpushs_same_cat'] != $new['lanpushs_same_cat']){
                $msg[] = '同品类地推数由‘'.$old['lanpushs_same_cat'].'’变成‘'.$new['lanpushs_same_cat'].'’';
            }
            if($old['frames_same_cat'] != $new['frames_same_cat']){
                $msg[] = '同品类端架数由‘'.$old['frames_same_cat'].'’变成‘'.$new['frames_same_cat'].'’';
            }
            if($old['zipcode'] != $new['zipcode']){
                $msg[] = '邮编由‘'.$old['zipcode'].'’变成‘'.$new['zipcode'].'’';
            }
            if($old['zipcode'] != $new['zipcode']){
                $msg[] = '邮编由‘'.$old['zipcode'].'’变成‘'.$new['zipcode'].'’';
            }
            if($old['myarea'] != $new['myarea']){
                $msg[] = '系统自编区域由‘'.$old['myarea'].'’变成‘'.$new['myarea'].'’';
            }
            if($old['mysn'] != $new['mysn']){
                $msg[] = '系统自编店号由‘'.$old['mysn'].'’变成‘'.$new['mysn'].'’';
            }
            if($old['mypart'] != $new['mypart']){
                $msg[] = '系统自编分仓由‘'.$old['mypart'].'’变成‘'.$new['mypart'].'’';
            }
            if($old['mypart_code'] != $new['mypart_code']){
                $msg[] = '系统自编分仓代码由‘'.$old['mypart_code'].'’变成‘'.$new['mypart_code'].'’';
            }
            if($old['mypart_code'] != $new['mypart_code']){
                $msg[] = '系统自编分仓代码由‘'.$old['mypart_code'].'’变成‘'.$new['mypart_code'].'’';
            }
            if($old['cooptime'] != $new['cooptime']){
                $msg[] = '开始合作日期由‘'.date('Y-m-d',$old['cooptime']).'’变成‘'.date('Y-m-d',$new['cooptime']).'’';
            }
            if($old['starttime'] != $new['starttime']){
                $msg[] = '网点开店日期由‘'.date('Y-m-d',$old['starttime']).'’变成‘'.date('Y-m-d',$new['starttime']).'’';
            }

            if($old['isApp'] != $new['isApp']){
                if($old['isApp'] ==0)
                    $msg[] = '网点由待审状态变为审核通过';
                else
                    $msg[] = '网点由审核通过变为待审状态';
            }
            if($old['iskey'] != $new['iskey']){
                if($old['iskey'] ==0)
                    $msg[] = '网点由非重点被设置为重点';
                else
                    $msg[] = '网点由重点被设置为非重点';
            }
            if($old['direct'] != $new['direct']){
                if($old['direct'] ==0)
                    $msg[] = '网点由非直营被设置为直营';
                else
                    $msg[] = '网点由直营被设置为非直营';
            }
            if($old['guide'] != $new['guide']){
                if($old['guide'] ==0)
                    $msg[] = '网点由非导购网点被设置为导购网点';
                else
                    $msg[] = '网点由导购网点被设置为非导购网点';
            }
            if($old['sample'] != $new['sample']){
                if($old['sample'] ==0)
                    $msg[] = '网点由非样板网点被设置为样板网点';
                else
                    $msg[] = '网点由样板网点被设置为非样板网点';
            }
            if($old['isnew'] != $new['isnew']){
                if($old['isnew'] ==0)
                    $msg[] = '网点由非新进网点被设置为新进网点';
                else
                    $msg[] = '网点由新进网点被设置为非新进网点';
            }

            if($msg){
                $msg = '修改了编号为\''.$old['sn'].'\'的网点‘'.$old['title'].'’,'.implode(',',$msg);
                //插入日志
                Db::table('cg_net_log')->insert(['content'=>$msg,
                    'system_id'=>$new['id'],
                    'cuser'=>Session::get("employee_id"),
                    'ctime'=>time()
                ]);
            }

        }
    }
    /**
     * 修改附件
     * @return mixed
     */
    public function updateAttach(){
        $attach = $this->request->post('attach');
        $id = $this->request->param('id');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_net')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');
        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        Db::table('cg_net')->where(array('id'=>$id))->update($data);
        //记录日志-开始记录
        $this->log_end($id,$old);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_net'));
        }

        echo json_encode(['success'=>true,'msg'=>'修改成功']);
    }

    /**
     * 设定为重点网点
     * @throws \think\Exception
     */
    public function setImportAgency(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['iskey'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }

    /**
     * 取消设定为重点网点
     * @throws \think\Exception
     */
    public function unSetImportAgency(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['iskey'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }
    /**
     * 设定为导购网点
     * @throws \think\Exception
     */
    public function setGuideNet(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['guide'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }
    /**
     * 取消设定为导购网点
     * @throws \think\Exception
     */
    public function unSetGuideNet(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['guide'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }
    /**
     * 设定为自营网点
     * @throws \think\Exception
     */
    public function setDirectNet(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['direct'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }

    /**
     * 取消设定为自营网点
     * @throws \think\Exception
     */
    public function unSetDirectNet(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['direct'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }
    /**
     * 设定为样板网点
     * @throws \think\Exception
     */
    public function setSampleNet(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['sample'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }

    /**
     * 取消设定为样板网点
     * @throws \think\Exception
     */
    public function unSetSampleNet(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_net')->where(array('id'=>$id))->update(['sample'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设定成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设定失败"
            ]);die;
        }
    }

    public function map(){
        $id = $this->request->param('id');
        if($_POST){
            $data = [];
            $data['lng'] = $this->request->post('lng');
            $data['lat'] = $this->request->post('lat');
            $data['detailAddress'] = $this->request->post('detailAddress');

            $bool = Db::table('cg_net')->where('id',$id)->update($data);
            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);die;
            }
        }
        return $this->fetch();
    }

    //在地图上显示
    public function mapShow(){
        $id = $this->request->param('import');
        $where = [];
        if($id){
            $where['iskey'] = 1;
        }
        $data = db('cg_net')->where($where)->field('lat,lng,detailAddress,title,id')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }

    //批量设置重点
    public function batchSetKey(){
        if($_POST){

            $bool = true;
            $add = $this->request->post('data/a');
            if($add){
                $add = implode(',',$add);
                $t = db('cg_net')->where('id','in',$add)->update(['iskey'=>1]);
                if(false===$t)
                    $bool = false;
            }
            $quxiao = $this->request->post('quxiao/a');
            if($quxiao){
                $quxiao = implode(',',$quxiao);
                $t = db('cg_net')->where('id','in',$quxiao)->update(['iskey'=>0]);
                if(false===$t)
                    $bool = false;
            }
            if($bool){
                echo json_encode(['success'=>1,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>0,'msg'=>'error']);
            }
            die;
        }
        return $this->fetch();
    }
    //批量设置导购
    public function batchSetGuide(){
        if($_POST){

            $bool = true;
            $add = $this->request->post('data/a');
            if($add){
                $add = implode(',',$add);
                $t = db('cg_net')->where('id','in',$add)->update(['guide'=>1]);
                if(false===$t)
                    $bool = false;
            }
            $quxiao = $this->request->post('quxiao/a');
            if($quxiao){
                $quxiao = implode(',',$quxiao);
                $t = db('cg_net')->where('id','in',$quxiao)->update(['guide'=>0]);
                if(false===$t)
                    $bool = false;
            }
            if($bool){
                echo json_encode(['success'=>1,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>0,'msg'=>'error']);
            }
            die;
        }
        return $this->fetch();
    }
    //批量设置直营
    public function batchSetDirect(){
        if($_POST){

            $bool = true;
            $add = $this->request->post('data/a');
            if($add){
                $add = implode(',',$add);
                $t = db('cg_net')->where('id','in',$add)->update(['direct'=>1]);
                if(false===$t)
                    $bool = false;
            }
            $quxiao = $this->request->post('quxiao/a');
            if($quxiao){
                $quxiao = implode(',',$quxiao);
                $t = db('cg_net')->where('id','in',$quxiao)->update(['direct'=>0]);
                if(false===$t)
                    $bool = false;
            }
            if($bool){
                echo json_encode(['success'=>1,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>0,'msg'=>'error']);
            }
            die;
        }
        return $this->fetch();
    }
    //批量设置样板
    public function batchSetSample(){
        if($_POST){

            $bool = true;
            $add = $this->request->post('data/a');
            if($add){
                $add = implode(',',$add);
                $t = db('cg_net')->where('id','in',$add)->update(['sample'=>1]);
                if(false===$t)
                    $bool = false;
            }
            $quxiao = $this->request->post('quxiao/a');
            if($quxiao){
                $quxiao = implode(',',$quxiao);
                $t = db('cg_net')->where('id','in',$quxiao)->update(['sample'=>0]);
                if(false===$t)
                    $bool = false;
            }
            if($bool){
                echo json_encode(['success'=>1,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>0,'msg'=>'error']);
            }
            die;
        }
        return $this->fetch();
    }
    //批量设置样板
    public function batchClearLatLng(){
        if($_POST){

            $bool = true;
            $add = $this->request->post('data/a');
            if($add){
                $add = implode(',',$add);
                $t = db('cg_net')->where('id','in',$add)->update(['lat'=>null,'lng'=>null]);
                if(false===$t)
                    $bool = false;
            }

            if($bool){
                echo json_encode(['success'=>1,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>0,'msg'=>'error']);
            }
            die;
        }
        return $this->fetch();
    }
//返回网点树数据-从分区开始 --批量维护重点
    public function nettreeajax(){

        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $t4 = db('cg_system')
                            ->where([
                                'jxs'=>$v4['id']
                            ])
                            ->field('id,title')
                            ->select();//查系统

                        $data6 = [];
                        foreach($t4 as $t4_k =>$t4_v){
                            $temp6 = [];
                            $temp6['name'] = $t4_v['title'];
                            $t5 = db('cg_net')
                                ->where(['system_id'=>$t4_v['id']])
                                ->field('id,title,iskey')
                                ->select();//查网点
                            $data7 = [];
                            foreach ($t5 as $t5_k=>$t5_v){
                                $temp7 = [];
                                $temp7['name'] = $t5_v['title'];
                                $temp7['id'] = $t5_v['id'];
                                if($t5_v['iskey']==1){
                                    $temp7['checked'] = true;
                                }
                                $data7[] = $temp7;
                            }
                            $temp6['children'] = $data7;
                            $temp6["chkDisabled"]=true;
                            $temp6["nocheck"]=true;
                            $data6[] = $temp6;
                        }
//                        echo db('cg_net')->getLastSql();
                        $temp5['children'] = $data6;
                        $temp5["chkDisabled"]=true;
                        $temp5["nocheck"]=true;
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }

        //查询所有已选择为重点的网点id
        $ids = db('cg_net')->where('iskey',1)->field('id')->select();
        foreach ($ids as $k=>$v){
            $ids[$k] = $v['id'];
        }
        echo json_encode([
            'ids'=>$ids,
            'tree'=>$data2
        ]);
    }
//返回网点树数据-从分区开始 --批量维护导购
    public function nettreeajax_guide(){

        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $t4 = db('cg_system')
                            ->where([
                                'jxs'=>$v4['id']
                            ])
                            ->field('id,title')
                            ->select();//查系统

                        $data6 = [];
                        foreach($t4 as $t4_k =>$t4_v){
                            $temp6 = [];
                            $temp6['name'] = $t4_v['title'];
                            $t5 = db('cg_net')
                                ->where(['system_id'=>$t4_v['id']])
                                ->field('id,title,guide')
                                ->select();//查网点
                            $data7 = [];
                            foreach ($t5 as $t5_k=>$t5_v){
                                $temp7 = [];
                                $temp7['name'] = $t5_v['title'];
                                $temp7['id'] = $t5_v['id'];
                                if($t5_v['guide']==1){
                                    $temp7['checked'] = true;
                                }
                                $data7[] = $temp7;
                            }
                            $temp6['children'] = $data7;
                            $temp6["chkDisabled"]=true;
                            $temp6["nocheck"]=true;
                            $data6[] = $temp6;
                        }
//                        echo db('cg_net')->getLastSql();
                        $temp5['children'] = $data6;
                        $temp5["chkDisabled"]=true;
                        $temp5["nocheck"]=true;
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }

        //查询所有已选择为重点的网点id
        $ids = db('cg_net')->where('guide',1)->field('id')->select();
        foreach ($ids as $k=>$v){
            $ids[$k] = $v['id'];
        }
        echo json_encode([
            'ids'=>$ids,
            'tree'=>$data2
        ]);
    }
//返回网点树数据-从分区开始 --批量维护直营
    public function nettreeajax_direct(){

        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $t4 = db('cg_system')
                            ->where([
                                'jxs'=>$v4['id']
                            ])
                            ->field('id,title')
                            ->select();//查系统

                        $data6 = [];
                        foreach($t4 as $t4_k =>$t4_v){
                            $temp6 = [];
                            $temp6['name'] = $t4_v['title'];
                            $t5 = db('cg_net')
                                ->where(['system_id'=>$t4_v['id']])
                                ->field('id,title,direct')
                                ->select();//查网点
                            $data7 = [];
                            foreach ($t5 as $t5_k=>$t5_v){
                                $temp7 = [];
                                $temp7['name'] = $t5_v['title'];
                                $temp7['id'] = $t5_v['id'];
                                if($t5_v['direct']==1){
                                    $temp7['checked'] = true;
                                }
                                $data7[] = $temp7;
                            }
                            $temp6['children'] = $data7;
                            $temp6["chkDisabled"]=true;
                            $temp6["nocheck"]=true;
                            $data6[] = $temp6;
                        }
//                        echo db('cg_net')->getLastSql();
                        $temp5['children'] = $data6;
                        $temp5["chkDisabled"]=true;
                        $temp5["nocheck"]=true;
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }

        //查询所有已选择为重点的网点id
        $ids = db('cg_net')->where('direct',1)->field('id')->select();
        foreach ($ids as $k=>$v){
            $ids[$k] = $v['id'];
        }
        echo json_encode([
            'ids'=>$ids,
            'tree'=>$data2
        ]);
    }
//返回网点树数据-从分区开始 --批量维护样板
    public function nettreeajax_sample(){

        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $t4 = db('cg_system')
                            ->where([
                                'jxs'=>$v4['id']
                            ])
                            ->field('id,title')
                            ->select();//查系统

                        $data6 = [];
                        foreach($t4 as $t4_k =>$t4_v){
                            $temp6 = [];
                            $temp6['name'] = $t4_v['title'];
                            $t5 = db('cg_net')
                                ->where(['system_id'=>$t4_v['id']])
                                ->field('id,title,sample')
                                ->select();//查网点
                            $data7 = [];
                            foreach ($t5 as $t5_k=>$t5_v){
                                $temp7 = [];
                                $temp7['name'] = $t5_v['title'];
                                $temp7['id'] = $t5_v['id'];
                                if($t5_v['sample']==1){
                                    $temp7['checked'] = true;
                                }
                                $data7[] = $temp7;
                            }
                            $temp6['children'] = $data7;
                            $temp6["chkDisabled"]=true;
                            $temp6["nocheck"]=true;
                            $data6[] = $temp6;
                        }
//                        echo db('cg_net')->getLastSql();
                        $temp5['children'] = $data6;
                        $temp5["chkDisabled"]=true;
                        $temp5["nocheck"]=true;
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }

        //查询所有已选择为重点的网点id
        $ids = db('cg_net')->where('sample',1)->field('id')->select();
        foreach ($ids as $k=>$v){
            $ids[$k] = $v['id'];
        }
        echo json_encode([
            'ids'=>$ids,
            'tree'=>$data2
        ]);
    }
//返回网点树数据-从分区开始 --清空网站经纬度
    public function nettreeajax_clearlat(){

        $data = Db::table('cg_market_zoning')
            ->where('isdel',0)
            ->field('id,title')
            ->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')
                ->where(array('zoning'=>$v['id']))
                ->field('id,title')
                ->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2 = [];
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')
                    ->where(array('provice'=>$vv['id']))
                    ->field('id,title')
                    ->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3 = [];
                    $temp3['name'] = $v3['title'];
                    $t3 = Db::table('cg_jxs')
                        ->where(array('city'=>$v3['id']))
                        ->field('id,title')
                        ->select();//查经销商
                    //查系统
                    $data5 = [];
                    foreach($t3 as $k4=>$v4){
                        $temp5 = [];
                        $temp5['name'] = $v4['title'];
                        $t4 = db('cg_system')
                            ->where([
                                'jxs'=>$v4['id']
                            ])
                            ->field('id,title')
                            ->select();//查系统

                        $data6 = [];
                        foreach($t4 as $t4_k =>$t4_v){
                            $temp6 = [];
                            $temp6['name'] = $t4_v['title'];
                            $t5 = db('cg_net')
                                ->where(['system_id'=>$t4_v['id']])
                                ->field('id,title,sample')
                                ->select();//查网点
                            $data7 = [];
                            foreach ($t5 as $t5_k=>$t5_v){
                                $temp7 = [];
                                $temp7['name'] = $t5_v['title'];
                                $temp7['id'] = $t5_v['id'];
                                $data7[] = $temp7;
                            }
                            $temp6['children'] = $data7;
                            $temp6["chkDisabled"]=true;
                            $temp6["nocheck"]=true;
                            $data6[] = $temp6;
                        }
//                        echo db('cg_net')->getLastSql();
                        $temp5['children'] = $data6;
                        $temp5["chkDisabled"]=true;
                        $temp5["nocheck"]=true;
                        $data5[] = $temp5;
                    }

                    $temp3['children'] = $data5;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }

        echo json_encode($data2);
    }

    //批量更新网点所属行政区域
    public function batchexec(){
        if($_POST){
           /* $bool = is_file('batchexec.lock');
            if(!$bool){
           */
            ignore_user_abort(true); // 后台运行
            set_time_limit(0); // 取消脚本运行时间的超时上限
            ob_end_clean();
            ob_implicit_flush(1);
                //执行匹配
                $data = db('cg_net')->field('id,lat,lng,title')->select();//查找所有网点
                $i = 1;
                foreach($data as $k=>$v){
                    $lat = $v['lat'];
                    $lng = $v['lng'];
                    if($lat){
                        //根据经纬度调用百度地图的接口查询对应行政省、市、区
                        $rs = file_get_contents('http://api.map.baidu.com/geocoder/v2/?ak=1IMGhA8nTnmf6LMGCLcVQaBt9TDWxoGc&location='.$lat.','.$lng.'&output=json&pois=1');
                        $rs = json_decode($rs);

                        $provice = $rs->result->addressComponent->province;
                        $city = $rs->result->addressComponent->city;
                        $district = $rs->result->addressComponent->district;

                        //查找行政省份对应的id
                        $provice_id = db('cg_provice')->where('title',trim($provice))->value('id');
                        if($provice_id)
                            db('cg_net')->where('id',$v['id'])->update(['exec_provice',$provice_id]);
                        else{
                            $insert = ['net_id'=>$v['id'],'content'=>$provice.'在系统没有维护，请联系管理员！','ctime'=>time(),'cuser'=>Session::get('employee_id')];
                            db('cg_net_batchexec_log')->insert($insert);
                            $insert['net_id']= $v['title'];
                            $insert['cuser'] = db('users')->where('id',$insert['cuser'])->value('login_name');
                            $insert['ctime'] = date('Y-m-d H:i',$insert['ctime']);
                            $insert['i'] = $i;$i++;


//                            header("HTTP/1.1 200 OK");
//                            ob_start();#开始当前代码缓冲

                            echo json_encode($insert);
                            sleep(1);
                            //下面输出http的一些头信息
//                            $size=ob_get_length();
//                            header("Content-Length: $size");
//                            ob_end_flush();#输出当前缓冲
//                            flush();#输出PHP缓冲

                        }


                        //查找行政城市对应的id
                        $city_id = db('cg_city')->where('title',trim($city))->value('id');
                        if($city_id)
                            db('cg_net')->where('id',$v['id'])->update(['exec_city',$city_id]);
                        else{
                            $insert = ['net_id'=>$v['id'],'content'=>$city.'在系统没有维护，请联系管理员！','ctime'=>time(),'cuser'=>Session::get('employee_id')];
                            db('cg_net_batchexec_log')->insert($insert);
                            $insert['net_id']= $v['title'];
                            $insert['cuser'] = db('users')->where('id',$insert['cuser'])->value('login_name');
                            $insert['ctime'] = date('Y-m-d H:i',$insert['ctime']);
                            $insert['i'] = $i;$i++;

//                            ob_end_clean();
//                            header("HTTP/1.1 200 OK");
//                            ob_implicit_flush(1);
//                            ob_start();#开始当前代码缓冲
                            echo json_encode($insert);
                            sleep(1);
                            //下面输出http的一些头信息
//                            $size=ob_get_length();
//                            header("Content-Length: $size");
//                            ob_end_flush();#输出当前缓冲
//                            flush();#输出PHP缓冲
                        }

                        //查找行政城市对应的id
                        $county_id = db('cg_county')->where('title',trim($district))->value('id');
                        if($city_id)
                            db('cg_net')->where('id',$v['id'])->update(['exec_county',$county_id]);
                        else{
                            $insert = ['net_id'=>$v['id'],'content'=>$district.'在系统没有维护，请联系管理员！','ctime'=>time(),'cuser'=>Session::get('employee_id')];
                            db('cg_net_batchexec_log')->insert($insert);
                            $insert['net_id']= $v['title'];
                            $insert['cuser'] = db('users')->where('id',$insert['cuser'])->value('login_name');
                            $insert['ctime'] = date('Y-m-d H:i',$insert['ctime']);
                            $insert['i'] = $i;$i++;

//                            ob_end_clean();
//                            ob_implicit_flush(1);
//                            header("HTTP/1.1 200 OK");
//                            ob_start();#开始当前代码缓冲
                            echo json_encode($insert);
                            sleep(1);
                            //下面输出http的一些头信息
//                            $size=ob_get_length();
//                            header("Content-Length: $size");
//                            ob_end_flush();#输出当前缓冲
//                            flush();#输出PHP缓冲

                        }

                    }

                }
            /*}else{
                echo json_encode(['success'=>0,'msg'=>'程序正在运行！']);

            }*/

            die;
        }
        return $this->fetch();
    }

    public function do1(){
        /* $bool = is_file('batchexec.lock');
            if(!$bool){
           */
        ignore_user_abort(true); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        ob_end_clean();
        ob_implicit_flush(1);
        //执行匹配
        $data = db('cg_net')->field('id,lat,lng,title')->select();//查找所有网点
        $i = 1;
        foreach($data as $k=>$v){
            $lat = $v['lat'];
            $lng = $v['lng'];
            if($lat){
                //根据经纬度调用百度地图的接口查询对应行政省、市、区
                $rs = file_get_contents('http://api.map.baidu.com/geocoder/v2/?ak=1IMGhA8nTnmf6LMGCLcVQaBt9TDWxoGc&location='.$lat.','.$lng.'&output=json&pois=1');
                $rs = json_decode($rs);

                $provice = $rs->result->addressComponent->province;
                $city = $rs->result->addressComponent->city;
                $district = $rs->result->addressComponent->district;

                //查找行政省份对应的id
                $provice_id = db('cg_provice')->where('title',trim($provice))->value('id');
                if($provice_id)
                    db('cg_net')->where('id',$v['id'])->update(['exec_provice',$provice_id]);
                else{
                    $insert = ['net_id'=>$v['id'],'content'=>$provice.'在系统没有维护，请联系管理员！','ctime'=>time(),'cuser'=>Session::get('employee_id')];
                    db('cg_net_batchexec_log')->insert($insert);
                    $insert['net_id']= $v['title'];
                    $insert['cuser'] = db('users')->where('id',$insert['cuser'])->value('login_name');
                    $insert['ctime'] = date('Y-m-d H:i',$insert['ctime']);
                    $insert['i'] = $i;$i++;


//                            header("HTTP/1.1 200 OK");
//                            ob_start();#开始当前代码缓冲

                    echo json_encode($insert);
                    echo <<<EOF
<div class="row">
    <div class="col-xs-2">{$insert['net_id']}</div>
    <div class="col-xs-2">{$insert['net_id']}</div>
    <div class="col-xs-2">{$insert['content']}</div>
    <div class="col-xs-2">{$insert['cuser']}</div>
    <div class="col-xs-2">{$insert['ctime']}</div>
</div>
EOF;

                    sleep(1);
                    //下面输出http的一些头信息
//                            $size=ob_get_length();
//                            header("Content-Length: $size");
//                            ob_end_flush();#输出当前缓冲
//                            flush();#输出PHP缓冲

                }


                //查找行政城市对应的id
                $city_id = db('cg_city')->where('title',trim($city))->value('id');
                if($city_id)
                    db('cg_net')->where('id',$v['id'])->update(['exec_city',$city_id]);
                else{
                    $insert = ['net_id'=>$v['id'],'content'=>$city.'在系统没有维护，请联系管理员！','ctime'=>time(),'cuser'=>Session::get('employee_id')];
                    db('cg_net_batchexec_log')->insert($insert);
                    $insert['net_id']= $v['title'];
                    $insert['cuser'] = db('users')->where('id',$insert['cuser'])->value('login_name');
                    $insert['ctime'] = date('Y-m-d H:i',$insert['ctime']);
                    $insert['i'] = $i;$i++;

//                            ob_end_clean();
//                            header("HTTP/1.1 200 OK");
//                            ob_implicit_flush(1);
//                            ob_start();#开始当前代码缓冲
                    echo json_encode($insert);
                    sleep(1);
                    //下面输出http的一些头信息
//                            $size=ob_get_length();
//                            header("Content-Length: $size");
//                            ob_end_flush();#输出当前缓冲
//                            flush();#输出PHP缓冲
                }

                //查找行政城市对应的id
                $county_id = db('cg_county')->where('title',trim($district))->value('id');
                if($city_id)
                    db('cg_net')->where('id',$v['id'])->update(['exec_county',$county_id]);
                else{
                    $insert = ['net_id'=>$v['id'],'content'=>$district.'在系统没有维护，请联系管理员！','ctime'=>time(),'cuser'=>Session::get('employee_id')];
                    db('cg_net_batchexec_log')->insert($insert);
                    $insert['net_id']= $v['title'];
                    $insert['cuser'] = db('users')->where('id',$insert['cuser'])->value('login_name');
                    $insert['ctime'] = date('Y-m-d H:i',$insert['ctime']);
                    $insert['i'] = $i;$i++;

//                            ob_end_clean();
//                            ob_implicit_flush(1);
//                            header("HTTP/1.1 200 OK");
//                            ob_start();#开始当前代码缓冲
                    echo json_encode($insert);

                    sleep(1);
                    //下面输出http的一些头信息
//                            $size=ob_get_length();
//                            header("Content-Length: $size");
//                            ob_end_flush();#输出当前缓冲
//                            flush();#输出PHP缓冲

                }

            }

        }
        /*}else{
            echo json_encode(['success'=>0,'msg'=>'程序正在运行！']);

        }*/
    }

    /**
     * 添加导购信息
     */
    public function tjdgxx(){
        if($_POST){
            $dgid = $this->request->post('dgid/a');
            $id = $this->request->param('id');
            $ins = [];
            foreach($dgid as $k=>$v){
                $ins[] = ['dg_id'=>$v,'net_id'=>$id,'xm'=>db('employee')->where('id',$v)->value('em_name')];
            }
            $bool = db('cg_net_dg')->insertAll($ins);
            if(false !== $bool)
                echo json_encode(['success'=>true,'msg'=>'ok']);
            else
                echo json_encode(['success'=>false,'msg'=>'error']);
            die;
        }
       return $this->fetch();
    }
}
